//
//  LJFChooseGiftViewController.m
//  GiftThat
//
//  Created by 刘景峰 on 16/1/12.
//  Copyright © 2016年 ChuXiang. All rights reserved.
//

#import "LJFChooseGiftViewController.h"
#import "LJFListModel.h"
#import "LJFListCollectionViewCell.h"
#import "LJFHotCollectionViewCell.h"
#import <MJRefresh.h>
#import "LJFModel.h"
#import "LJFNewHotViewController.h"
static NSString *urlString = @"http://api.liwushuo.com/v2/search/item_filter";
static NSString *mainURLString = @"http://api.liwushuo.com/v2/search/item_by_type?limit=20&offset=0";

@interface LJFChooseGiftViewController ()<UICollectionViewDelegate,UICollectionViewDataSource>
@property (nonatomic,strong) NSMutableArray *bigArray;
@property (nonatomic,strong) NSMutableArray *bigModelArray;
@property (nonatomic,assign) BOOL jianTou;
@property (nonatomic,strong) UICollectionView *collectionView;
@property (nonatomic,strong) UIView *buttonView;
@property (nonatomic,strong) UIView *bigView;
@property (nonatomic,strong) NSMutableArray *mainMuArray;
@property (nonatomic,strong) UIButton *button;
@property (nonatomic,strong) NSArray *useArray;
@property (nonatomic,strong) UICollectionView *mainCollectionView;
@property (nonatomic,copy) NSString *nextPageUrl;
@end
static NSString *cellName = @"LJFListCollectionViewCell";
static NSString *mainCellName = @"LJFMainCollectionViewCell";
@implementation LJFChooseGiftViewController

-(void)viewWillAppear:(BOOL)animated{
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:@"Color"] isEqualToString:@"BlackColor"]) {
        self.view.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        self.mainCollectionView.backgroundColor = [UIColor colorWithRed:35 / 255.0 green:34 / 255.0 blue:38 / 255.0 alpha:1.0];
        [self.mainCollectionView reloadData];
    }else{
        self.mainCollectionView.backgroundColor =  [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1.0];
        self.view.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1.0];
        [self.mainCollectionView reloadData];
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
//    数组初始化
    self.jianTou = YES;
    self.mainMuArray = [NSMutableArray array];
    self.bigArray = [NSMutableArray array];
    self.bigModelArray = [NSMutableArray array];
    self.useArray = [NSArray array];
//    self.view.backgroundColor = [UIColor whiteColor];
//    self.view.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
//   铺界面的collectionview及网络请求
    [self getMainURL:mainURLString];
    [self creatMainCollectionView];
    
    NSArray *array = @[@"对象",@"综合",@"个性",@"价格"];
    
    self.buttonView= [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 40)];
    self.buttonView.backgroundColor = [UIColor whiteColor];
    
    [self.view addSubview:self.buttonView];

    for (int i = 0; i < 4; i++) {
        
        self.button = [UIButton buttonWithType:UIButtonTypeSystem];

        _button.tag = 100 + i;
        _button.tintColor = [UIColor blackColor];
        _button.frame = CGRectMake(i *self.view.width/4 + 1, 0, self.view.width / 4 - 2,self.buttonView.height);
        [_button setTitle:array[i] forState:UIControlStateNormal];
        [_button addTarget:self action:@selector(buttonDid:) forControlEvents:UIControlEventTouchUpInside];
        
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"down"]];
        imageView.frame = CGRectMake(0, 0, 10, 10);
        imageView.center = CGPointMake(_button.width - 10, _button.center.y);
        imageView.tag = i + 1000;
        
        [self.buttonView addSubview:_button];
        [_button addSubview:imageView];
    }

}

#pragma mark-collectionview创建以及方法
-(void)creatCollectionView:(NSInteger)tag{
//放collectionview的uiview
    
    if (self.bigView) {
        [self.view addSubview:self.bigView];
        [self.bigView addSubview:self.collectionView];
    }else{
    self.bigView = [[UIView alloc]initWithFrame:CGRectMake(0, self. buttonView.height, self.view.width, self.view.height - self.buttonView.height)];
    self.bigView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:self.bigView];
        
        UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
        
        flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
        flowLayout.minimumLineSpacing = 5.0;
        flowLayout.itemSize = CGSizeMake((self.view.width - 30) / 3, 30);
        
        self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, self.view.width, 150) collectionViewLayout:flowLayout];
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;

        [self.collectionView registerClass:[LJFListCollectionViewCell class] forCellWithReuseIdentifier:cellName];
        self.collectionView.backgroundColor = [UIColor whiteColor];
        self.collectionView.alpha = 1;
        [self.bigView addSubview:self.collectionView];
        
        
        UIImageView *imageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"lingImage"]];
        imageView.frame = CGRectMake(0, self.collectionView.bottom - 40, self.collectionView.width, 40);
        [self.collectionView addSubview:imageView];
        
    }

}


-(void)creatMainCollectionView{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc]init];
    flowLayout.scrollDirection = UICollectionViewScrollDirectionVertical;
    flowLayout.minimumInteritemSpacing = CGFLOAT_MIN;
    flowLayout.minimumLineSpacing = 10;
    flowLayout.itemSize = CGSizeMake((self.view.frame.size.width - 10)/2,200);
    
    self.mainCollectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(5, 40, self.view.frame.size.width - 10, self.view.frame.size.height - 113) collectionViewLayout:flowLayout];
    self.mainCollectionView.backgroundColor = [UIColor colorWithRed:234 / 255.0 green:234 / 255.0 blue:241 / 255.0 alpha:1];
    self.mainCollectionView.showsVerticalScrollIndicator = NO;
    self.mainCollectionView.delegate = self;
    self.mainCollectionView.dataSource = self;
    [self.mainCollectionView registerClass:[LJFHotCollectionViewCell class] forCellWithReuseIdentifier:mainCellName];
    //    collectionview的上拉加载
    
    self.mainCollectionView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footDid)];

    
    [self.view addSubview:self.mainCollectionView];
    
    
}

-(void)footDid{

    [self getMainURL:self.nextPageUrl];

}

-(void)dismissCollectionView{
    [self.bigView removeAllSubviews];
    [self.bigView removeFromSuperview];
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.collectionView == collectionView) {
        return self.useArray.count;
    }else{
        return self.mainMuArray.count;
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    if ([self.collectionView isEqual:collectionView]) {
        LJFListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellName forIndexPath:indexPath];

        if (self.useArray.count > indexPath.item) {
            LJFListModel *liset = self.useArray[indexPath.item];
            cell.listModel = liset;
        }
        return cell;
   
    }else{
        LJFHotCollectionViewCell  *hotCell = [collectionView dequeueReusableCellWithReuseIdentifier:mainCellName forIndexPath:indexPath];

        if (self.mainMuArray.count > indexPath.item) {
            LJFModel *ljfModel = self.mainMuArray[indexPath.item];
        hotCell.ljfmodel = ljfModel;
            
        }
        return hotCell;
    }
}

#pragma mark-button的点击事件
-(void)buttonDid:(UIButton *)button{
    NSInteger a = button.tag % 10;
    
    for (int i = 0; i < 4; i++) {
        NSInteger tag = 1000 + i;
        if (tag != button.tag) {
            UIImageView *imagrView = [self.view viewWithTag:tag];
            imagrView.image = [UIImage imageNamed:@"down"];
        }
    }
    if (self.jianTou == YES) {
    UIImageView *imageView = [self.view viewWithTag:1000 + a];
    [imageView setImage:[UIImage imageNamed:@"up"]];
        self.jianTou = NO;
        [self getURL:a];
        [self creatCollectionView:a];
    }else {
    UIImageView *imageView = [self.view viewWithTag:1000 + a];
    [imageView setImage:[UIImage imageNamed:@"down"]];
        self.jianTou = YES;
        [self dismissCollectionView];
    }
}

#pragma mark-网络请求 用来铺下拉菜单的cell数据
-(void)getURL:(NSInteger)tag{
    [CXNetWorkTool getWithUrl:urlString parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
        NSDictionary *dic = [result objectForKey:@"data"];
        NSArray *array = [dic objectForKey:@"filters"];
        for (NSDictionary *dic in array) {
          NSArray *arr = [dic objectForKey:@"channels"];
            NSMutableArray *muArray = [NSMutableArray array];
            for (NSDictionary *dic2 in arr) {
                LJFListModel *listModel = [[LJFListModel alloc] initWithDictionary:dic2];
                [muArray addObject:listModel];
            }
            [self.bigModelArray addObject:muArray];
        }
        self.useArray = self.bigModelArray[tag];
        [self.collectionView reloadData];
    } fail:^(NSError *error) {
        NSLog(@"%@",error);
    }];
}

-(void)getMainURL:(NSString *)url{
    
    if (url != self.nextPageUrl) {
        [self.mainMuArray removeAllObjects];
    }
    
    if ([url isEqual:[NSNull null]]) {
        [self.collectionView.mj_footer endRefreshing];
    }else{
        [CXNetWorkTool getWithUrl:url parameter:nil httpHeader:nil responseType:ResponseTypeJSON success:^(id result) {
            
            NSDictionary *dic = result;
            NSDictionary *dic1 = [dic objectForKey:@"data"];
            NSArray *array = [dic1 objectForKey:@"items"];
            //        获取下一页的url
            NSDictionary *dic2 = [[NSDictionary alloc]initWithDictionary:[dic1 objectForKey:@"paging"]];
            self.nextPageUrl  = [dic2 objectForKey:@"next_url"];
            for (NSDictionary *dic3 in array) {
                LJFModel *hot = [[LJFModel alloc]initWithDictionary:dic3];
                [self.mainMuArray addObject:hot];
            }
            [self.mainCollectionView reloadData];
            [self.mainCollectionView.mj_footer endRefreshing];
        } fail:^(NSError *error) {
            NSLog(@"%@",error);
        }];
    }

    
}


-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([self.mainCollectionView isEqual:collectionView]) {
        LJFNewHotViewController *new = [[LJFNewHotViewController alloc]init];
        NSString *string = @"http://www.liwushuo.com/items/%@";
        LJFModel *model = self.mainMuArray[indexPath.item];
        NSString *newString = [NSString stringWithFormat:string,model.NewId];
        new.urlString = newString;
        [self.navigationController pushViewController:new animated:YES];
        
    }else{
        NSString *string = @"http://api.liwushuo.com/v2/search/item_by_type?limit=20&offset=0";
        LJFListModel *list = self.useArray[indexPath.item];
        LJFListModel *firstOne  =  [self.useArray firstObject];
        NSString *newString = [[NSString alloc]init];
        if ([firstOne.name isEqualToString:@"男票"]) {
            newString = [string stringByAppendingString:@"&target="];
        }else if ([firstOne.name isEqualToString:@"生日"]){
            newString = [string stringByAppendingString:@"&scene="];
        }else if ([firstOne.name isEqualToString:@"萌"]){
            newString = [string stringByAppendingString:@"&personality="];
        }else{
            newString = [string stringByAppendingString:@"&price="];
        }
        NSString *newString1 = [NSString stringWithFormat:@"%@",list.key];
        NSString *finalString = [newString stringByAppendingString:newString1];
        [self getMainURL:finalString];
    }
 
}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
